package com.ran.java_gobang.api;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-08-26
 * Time: 20:49
 */
@Component
public class TestAPI extends TextWebSocketHandler {
    /**
     * 连接建立后触发的方法
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功!");
    }

    /**
     * 客户端给服务器发送文本消息用该方法可以感知到
     * @param session 建立连接时的 websocket 回话
     * @param message 拿到数据的文本载荷
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());// 拿到数据的文本载荷
        session.sendMessage(message);
    }

    /**
     * 传输异常触发
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("连接异常!");
    }

    /**
     * 连接被关闭触发
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接关闭!");
    }
}
